import { Inject, Injectable, OnModuleInit } from '@nestjs/common';
import { PrismaClient } from '@prisma/client';
import { PrismaModuleOptions, PrismaOptionsFactory } from './prisma-options.interface';
import { REQUEST } from '@nestjs/core';

@Injectable()
export class PrismaService extends PrismaClient implements OnModuleInit, PrismaOptionsFactory {

    constructor(@Inject(REQUEST) private request: Request) {
        super();
    }
    
    createPrismaModuleOptions(): any {
        const headers = this.request.headers
        const tenantId = headers['x-tenant-id'] || 'default'
        if(tenantId == 'default') {
            return {
                url: 'mysql://root:123456@127.0.0.1:3306/testdb'
            }
        }
    }

    //实例化 PrismaClient 并连接到数据库
    async onModuleInit() {
        // await this.$connect();   // 使用的是@prisma/client的PrismaClient
    }
}